package com.qfedu.common.exception;

import com.qfedu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 2024/12/26 上午11:07
 * 全局异常处理类
 * 一般异常信息存入日志
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CommonException.class)
    public R commonExceptionHandler(CommonException e) {

        log.error("异常信息:{}", e.getMsg());
        return R.fail(e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {

        log.error(e.getMessage());
        return R.fail("未知异常，请联系管理员：错误信息 => " + e.getMessage());
    }

    /**
     * 验证登录
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R verificationExceptionHandler(ConstraintViolationException e) {
        // 获取对应的迭代器
        for (ConstraintViolation<?> next : e.getConstraintViolations()) {
            // 获取异常信息
            System.out.println(next.getMessage());
        }
        return R.fail("参数校验失败");
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R exceptionHandler(MethodArgumentNotValidException e) {
        // StringBuilder sbf = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
        return R.fail(500, message);
    }

}
